package com.thiswhyme.demo.msgpush.core;

import cn.hutool.json.JSONUtil;
import com.thiswhyme.demo.msgpush.core.event.bean.WebSocketEvent;
import com.thiswhyme.demo.msgpush.core.event.bean.EventType;
import com.thiswhyme.redis.subscribe.RedisPublisher;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @description: 消息推送服务
 * @author: thiswhyme
 * @date: 2021/9/28
 */
@Slf4j
@Service
@AllArgsConstructor
public class PushService {

    private final RedisPublisher redisPublisher;

    /**
     * 推送通知给单个指定目标
     * @param target
     * @param message
     */
    public void pushMessage(String target, String message) {
        pushMessage(Collections.singletonList(target), message);
    }

    /**
     * 推送通知给多个指定目标
     * @param targets
     * @param message
     */
    public void pushMessage(List<String> targets, String message) {
        WebSocketEvent event = new WebSocketEvent()
                .setEventType(EventType.PUSH)
                .setIdentifiers(targets)
                .setMsgContent(message);
        redisPublisher.publish(WsConstant.WS_MSG_PUSH_CHANNEL, JSONUtil.toJsonStr(event));
    }

    /**
     * 广播通知给所有目标
     * @param message
     */
    public void broadcast(String message) {
        WebSocketEvent event = new WebSocketEvent()
                .setEventType(EventType.BROADCAST)
                .setMsgContent(message);
        redisPublisher.publish(WsConstant.WS_MSG_PUSH_CHANNEL, JSONUtil.toJsonStr(event));
    }
}
